#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


from PySide import QtCore, QtGui

class SearchComboBox(QtGui.QComboBox):
    def __init__(self, parent=None):
        super(SearchComboBox, self).__init__(parent)
        self.setEditable(1)
        self.setFixedHeight(20)
        self.setInsertPolicy(QtGui.QComboBox.NoInsert)
        # self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
        # create list view
        self.list_view = QtGui.QListView(self)
        self._model = QtGui.QStringListModel(self)
        self._proxy_model = QtGui.QSortFilterProxyModel()
        self._proxy_model.setSourceModel(self._model)
        self.list_view.setWindowFlags(QtCore.Qt.ToolTip)
        self.list_view.setModel(self._proxy_model)
        self.list_view.setStyleSheet("""
        QListView{
            background:rgb(35,35,35);
            border:1px solid rgb(0, 120, 210);
        }
        QListView:item{
            height:15px;
        }
        QListView:item:hover,QListView:item:selected{
            background:rgb(0, 120, 210);
        }
        """)
        
        # connect
        self.editTextChanged.connect(self.setCompleter)
        self.currentIndexChanged.connect(self.list_view.hide)
        self.list_view.clicked.connect(self.completeText)
        self.setMouseTracking(True)
        self.list_view.setMouseTracking(True)
        # self.list_view.enterEvent = self._enter_event
        # self.list_view.leaveEvent = self._leave_event
        self._hide = True
        self.list_view.installEventFilter(self)

    def _set_view_hide(self):
        self.list_view.hide()

    def showPopup (self):
        self._set_view_hide()
        super(SearchComboBox, self).showPopup()

    def set_data(self, data=list()):
        self.addItems(data)
        self._model.setStringList(data)

    def clear_data(self):
        self.clear()
        self._model.setStringList([])

    def focusOutEvent(self, event):
        if self._hide:
            self._set_view_hide()
        super(SearchComboBox, self).focusOutEvent(event)
        
    def resizeEvent(self, event):
        self._set_view_hide()
        super(SearchComboBox, self).resizeEvent(event)

    def keyPressEvent(self, event):
        if not self.list_view.isHidden():
            key = event.key()
            count = self.list_view.model().rowCount()
            currentIndex = self.list_view.currentIndex()
            if QtCore.Qt.Key_Down == key:
                row = currentIndex.row() + 1
                if row >= count:
                    row = 0
                index = self.list_view.model().index(row, 0)
                self.list_view.setCurrentIndex(index)
            elif QtCore.Qt.Key_Up == key:
                row = currentIndex.row() - 1
                if row<0:
                    row = count-1
                index = self.list_view.model().index(row, 0)
                self.list_view.setCurrentIndex(index)
            elif QtCore.Qt.Key_Escape == key:
                self._set_view_hide()
            elif QtCore.Qt.Key_Enter == key or QtCore.Qt.Key_Return == key:
                if currentIndex.isValid():
                    text = self.list_view.currentIndex().data()
                    ind = self.findText(text, QtCore.Qt.MatchExactly)
                    self.setCurrentIndex(ind)
                self._set_view_hide()
            else:
                self._set_view_hide()
                super(SearchComboBox, self).keyPressEvent(event)
        else:
            super(SearchComboBox, self).keyPressEvent(event)

    def setCompleter(self, text):
        if not text:
            self._set_view_hide()
            return
        ind = self.findText(text, QtCore.Qt.MatchExactly)
        if ind == -1:
            self.setStyleSheet("""
            *{color:red;}
            QAbstractItemView{
            color:white;
            }
            """)
        else:
            self.setStyleSheet("color:white;")
        syntax = QtCore.QRegExp.PatternSyntax(QtCore.QRegExp.RegExp)
        regExp = QtCore.QRegExp(text, QtCore.Qt.CaseInsensitive, syntax)
        self._proxy_model.setFilterRegExp(regExp)
        if self._proxy_model.rowCount() == 0:

            return
        elif self._proxy_model.rowCount() < 10:
            height = self._proxy_model.rowCount()*15 +2
        else:
            height = 150+2

        self.list_view.setMaximumHeight(height)
        self.list_view.setMinimumHeight(height)
        self.list_view.setMinimumWidth(self.width())
        self.list_view.setMaximumWidth(self.width())
        self._set_view_pos()
        self.list_view.show()

    def _set_view_pos(self):
        point = QtCore.QPoint(0, self.height())
        x = self.mapToGlobal(point).x()
        y = self.mapToGlobal(point).y() # +1
        self.list_view.move(x, y)

    def completeText(self, index):
        text = index.data()
        ind = self.findText(text, QtCore.Qt.MatchExactly)
        self.setCurrentIndex(ind)
        self._set_view_hide()

    def eventFilter(self, obj, event):
        if obj == self.list_view:
            if event.type() == QtCore.QEvent.Enter:
                self._hide = False
            elif event.type() == QtCore.QEvent.Leave:
                self._hide = True
        return super(SearchComboBox, self).eventFilter(obj, event)





